from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django.db.models import Count, Avg
from .models import Cluster, Node, Instance, ResourceUsage
from .serializers import (
    ClusterSerializer, NodeSerializer, InstanceSerializer,
    ResourceUsageSerializer
)

class ClusterViewSet(viewsets.ModelViewSet):
    queryset = Cluster.objects.all()
    serializer_class = ClusterSerializer
    permission_classes = [IsAuthenticated]

    def perform_create(self, serializer):
        serializer.save(created_by=self.request.user)

class NodeViewSet(viewsets.ModelViewSet):
    queryset = Node.objects.all()
    serializer_class = NodeSerializer
    permission_classes = [IsAuthenticated]

    def perform_create(self, serializer):
        serializer.save(created_by=self.request.user)

    @action(detail=True, methods=['get'])
    def resource_usage(self, request, pk=None):
        node = self.get_object()
        usage = ResourceUsage.objects.filter(node=node).order_by('-timestamp')[:100]
        serializer = ResourceUsageSerializer(usage, many=True)
        return Response(serializer.data)

class InstanceViewSet(viewsets.ModelViewSet):
    queryset = Instance.objects.all()
    serializer_class = InstanceSerializer
    permission_classes = [IsAuthenticated]

    def perform_create(self, serializer):
        serializer.save(created_by=self.request.user)

    @action(detail=True, methods=['get'])
    def resource_usage(self, request, pk=None):
        instance = self.get_object()
        usage = ResourceUsage.objects.filter(instance=instance).order_by('-timestamp')[:100]
        serializer = ResourceUsageSerializer(usage, many=True)
        return Response(serializer.data)

    @action(detail=True, methods=['post'])
    def start(self, request, pk=None):
        instance = self.get_object()
        instance.status = 'running'
        instance.save()
        return Response({'status': 'instance started'})

    @action(detail=True, methods=['post'])
    def stop(self, request, pk=None):
        instance = self.get_object()
        instance.status = 'stopped'
        instance.save()
        return Response({'status': 'instance stopped'})

class DashboardViewSet(viewsets.ViewSet):
    permission_classes = [IsAuthenticated]

    def list(self, request):
        # 获取系统统计数据
        stats = {
            'totalClusters': Cluster.objects.count(),
            'totalNodes': Node.objects.count(),
            'totalInstances': Instance.objects.count(),
            'resourceUsage': self._calculate_resource_usage()
        }
        return Response(stats)

    def _calculate_resource_usage(self):
        # 计算总体资源使用率
        nodes = Node.objects.all()
        if not nodes:
            return 0
        
        total_cpu = sum(node.cpu_cores for node in nodes)
        total_memory = sum(node.memory_gb for node in nodes)
        total_disk = sum(node.disk_gb for node in nodes)
        
        used_cpu = sum(instance.cpu_cores for instance in Instance.objects.filter(status='running'))
        used_memory = sum(instance.memory_gb for instance in Instance.objects.filter(status='running'))
        used_disk = sum(instance.disk_gb for instance in Instance.objects.filter(status='running'))
        
        if total_cpu + total_memory + total_disk == 0:
            return 0
            
        return round(((used_cpu + used_memory + used_disk) / (total_cpu + total_memory + total_disk)) * 100, 2)

    @action(detail=False, methods=['get'])
    def load_distribution(self, request):
        # 获取系统负载分布
        total_instances = Instance.objects.count()
        if total_instances == 0:
            return Response({
                'normal': 0,
                'warning': 0,
                'critical': 0
            })
            
        normal = Instance.objects.filter(status='running').count()
        warning = Instance.objects.filter(status='stopped').count()
        critical = Instance.objects.filter(status='error').count()
        
        return Response({
            'normal': normal,
            'warning': warning,
            'critical': critical
        })

    @action(detail=False, methods=['get'])
    def recent_activities(self, request):
        # 获取最近活动
        activities = []
        
        # 获取最近的实例操作
        recent_instances = Instance.objects.order_by('-created_at')[:5]
        for instance in recent_instances:
            activities.append({
                'id': f'instance_{instance.id}',
                'type': 'success',
                'timestamp': instance.created_at,
                'content': f'创建实例: {instance.name}'
            })
            
        # 获取最近的节点操作
        recent_nodes = Node.objects.order_by('-created_at')[:5]
        for node in recent_nodes:
            activities.append({
                'id': f'node_{node.id}',
                'type': 'info',
                'timestamp': node.created_at,
                'content': f'添加节点: {node.name}'
            })
            
        # 按时间排序
        activities.sort(key=lambda x: x['timestamp'], reverse=True)
        return Response(activities[:10])  # 只返回最近10条活动 